import pandas as pd

# 读取 CSV 文件
file_path = 'result_detail.csv'  
#存放终端输出的文件路径
terminal_file_path = "result.txt"

# 从文件中提取Total Time
def extract_total_time(path):
    with open(path, 'r') as file:
        for line in file:
            if "Total Time:" in line:
                time_part = line.split("Total Time: ")[1]
                time_part = time_part.split("ms")[0]
                return float(time_part)

df = pd.read_csv(file_path)

# 除第一列外的列名
columns = df.columns[1:]

f = open('result_detail_sum.csv', 'w')

# 写入列头,将file_path的第一行拷贝过来写入
with open(file_path, 'r') as file:
    #把总时间写在开头
    f.write("Total Time(ms),")
    first_line = file.readline()
    #将第一个逗号及前面的字符串去掉（qid，sum里面不需要该字段）
    first_line = first_line[first_line.find(',')+2:]
    f.write(first_line)
    
    # 提取Total Time
    total_time = extract_total_time(terminal_file_path)
    # 写入Total Time
    f.write(f"{total_time:.3f},")

# 计算每列的平均值
for column in columns:
    average = df[column].mean()
    variance = df[column].var()
    #最大值与最小值
    max_value = df[column].max()
    min_value = df[column].min()
    #求和
    sum_value = df[column].sum()
    #计算该值的方差
    print(f"{column.ljust(24)} 平均值: {average:.5f}  \t方差: {variance:.3f} \t范围: {min_value:.3f} - {max_value:.3f} \t求和: {sum_value:.3f}")

    #正常情况下写入平均值，可以指定写入其他值例如求和、方差等
    if 'trivial-1' in column or 'trivial-2' in column:
        f.write(f"{sum_value:.3f},")
    else:
        f.write(f"{average:.8f},")

f.close()